<template>
  <a-card title="流程实例列表" :loading="loading">
    <a-form layout="inline" @submit.prevent>
      <a-form-item label="Proc Def Key">
        <a-input v-model:value="filters.processDefinitionKey" placeholder="leaveApproval" style="width:160px" />
      </a-form-item>
      <a-form-item label="Started By">
        <a-input v-model:value="filters.startedBy" placeholder="(可选)" style="width:140px" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="reloadFirst">查询</a-button>
      </a-form-item>
      <a-form-item>
        <a-button danger :disabled="selectedRowKeys.length===0" @click="confirmBatchDelete">批量删除 ({{ selectedRowKeys.length }})</a-button>
      </a-form-item>
    </a-form>
    <a-table
      :columns="columns"
      :data-source="instances"
      row-key="id"
      size="small"
      :row-selection="rowSelection"
      :pagination="pagination"
      @change="handleTableChange"
      style="margin-top:12px" />
  </a-card>
</template>
<script setup lang="ts">
import { ref, h } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { listInstances, deleteProcessInstance } from '../services/flowable';

const loading = ref(false);
const instances = ref<any[]>([]);
const filters = ref({ processDefinitionKey: '', startedBy: '' });
const pagination = ref({ current: 1, pageSize: 20, total: 0, showSizeChanger: true, showTotal: (t:number)=>`共 ${t} 条` });
const selectedRowKeys = ref<string[]>([]);
const rowSelection = {
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: any[]) => { selectedRowKeys.value = keys as string[]; },
  preserveSelectedRowKeys: true
};

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 110 },
  { title: '流程定义名称', dataIndex: 'processDefinitionName', key: 'processDefinitionName' },
  { title: '流程定义ID', dataIndex: 'processDefinitionId', key: 'processDefinitionId' },
  { title: '业务Key', dataIndex: 'businessKey', key: 'businessKey' },
  { title: '启动用户(startUserId)', dataIndex: 'startUserId', key: 'startUserId', width: 140 },
  { title: '开始时间', dataIndex: 'startTime', key: 'startTime', width: 170 },
  { title: '结束', dataIndex: 'ended', key: 'ended', customRender: ({ text }: any) => text ? '✅' : '' },
  { title: '操作', key: 'action',
    customRender: ({ record }: any) => {
      if (record.ended) return '—';
      return h('a', { style: 'color:#ff4d4f', onClick: () => confirmDelete(record) }, '删除');
    }
  }
];

function confirmDelete(record: any) {
  Modal.confirm({
    title: '删除流程实例',
    content: `确定删除流程实例 ${record.id} ? 此操作不可撤销。`,
    okText: '删除',
    okType: 'danger',
    cancelText: '取消',
    async onOk() {
      try {
        await deleteProcessInstance(record.id, 'user_manual_delete');
        message.success('删除成功');
        await load();
      } catch (e: any) {
        message.error(e.message || '删除失败');
      }
    }
  });
}

async function load(page = pagination.value.current, pageSize = pagination.value.pageSize) {
  loading.value = true;
  try {
    const result = await listInstances({
      processDefinitionKey: filters.value.processDefinitionKey || undefined,
      startedBy: filters.value.startedBy || undefined,
      page,
      pageSize
    });
    instances.value = result.items;
    pagination.value.total = result.total;
    pagination.value.current = result.page;
    pagination.value.pageSize = result.pageSize;
    // 若当前页没有数据且不是第一页，自动跳回最后一页
    if (instances.value.length === 0 && pagination.value.current > 1 && result.total > 0) {
      const last = Math.ceil(result.total / pagination.value.pageSize);
      pagination.value.current = last;
      await load(last, pagination.value.pageSize);
    }
  } catch (e:any) {
    message.error(e.message || '加载失败');
  } finally {
    loading.value = false;
  }
}

function handleTableChange(pag:any) {
  pagination.value.current = pag.current;
  pagination.value.pageSize = pag.pageSize;
  load(pag.current, pag.pageSize);
}

function reloadFirst() {
  pagination.value.current = 1;
  load(1, pagination.value.pageSize);
}

function confirmBatchDelete() {
  if (selectedRowKeys.value.length === 0) return;
  Modal.confirm({
    title: '批量删除流程实例',
    content: `确定删除选中的 ${selectedRowKeys.value.length} 个流程实例？此操作不可撤销。`,
    okText: '删除',
    okType: 'danger',
    cancelText: '取消',
    async onOk() {
      loading.value = true;
      const errors: string[] = [];
      for (const id of selectedRowKeys.value) {
        try {
          await deleteProcessInstance(id, 'batch_delete');
        } catch (e: any) {
          errors.push(id + ':' + (e.message || '失败'));
        }
      }
      selectedRowKeys.value = [];
      await load();
      loading.value = false;
      if (errors.length) {
        message.error(`部分失败 (${errors.length})`);
        console.error('批量删除失败详情', errors);
      } else {
        message.success('批量删除成功');
      }
    }
  });
}

load();
</script>
